import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';

import 'package:get/get.dart';
import 'package:xmshop/app/services/duanzihuangFonts.dart';
import 'package:xmshop/app/services/httpsClient.dart';
import 'package:xmshop/app/services/keepAliveWrapper.dart';
import 'package:xmshop/app/services/screenAdapter.dart';

import '../controllers/home_controller.dart';

class HomeView extends GetView<HomeController> {
  const HomeView({Key? key}) : super(key: key);

  Widget _focus() {
    return SizedBox(
      width: ScreenAdapter.width(1080),
      height: ScreenAdapter.height(682),
      child: Obx(() => Swiper(
            itemCount: controller.swiperList.length,
            itemBuilder: (context, index) {
              String picUrl =
                  "https://xiaomi.itying.com/${controller.swiperList[index].pic}";
              return Image.network(picUrl.replaceAll("\\", "/"),
                  fit: BoxFit.fill);
            },
            pagination: const SwiperPagination(builder: SwiperPagination.rect),
            autoplay: true,
            loop: true,
          )),
    );
  }

  Widget _banner() {
    return SizedBox(
        width: ScreenAdapter.width(1080),
        height: ScreenAdapter.height(92),
        child:
            Image.asset("assets/images/xiaomiBanner.png", fit: BoxFit.cover));
  }

  // 顶部互动分类
  Widget _category() {
    return SizedBox(
      width: ScreenAdapter.width(1080),
      height: ScreenAdapter.width(470),
      child: Obx(
        () => Swiper(
            itemCount: controller.categoryList.length ~/ 10,
            itemBuilder: (context, index) {
              return GridView.builder(
                  itemCount: 10,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 5,
                      crossAxisSpacing: ScreenAdapter.width(20),
                      mainAxisSpacing: ScreenAdapter.width(20)),
                  itemBuilder: (context, i) {
                    String picUrl =
                        "https://xiaomi.itying.com/${controller.categoryList[index * 10 + i].pic}";
                    return Column(
                      children: [
                        Container(
                          alignment: Alignment.center,
                          width: ScreenAdapter.height(140),
                          height: ScreenAdapter.height(140),
                          child: Image.network(picUrl.replaceAll("\\", "/"),
                              fit: BoxFit.fitHeight),
                        ),
                        Padding(
                            padding: EdgeInsets.fromLTRB(
                                0, ScreenAdapter.height(4), 0, 0),
                            child: Text(
                                "${controller.categoryList[index * 10 + i].title}",
                                style: TextStyle(
                                    fontSize: ScreenAdapter.fontSize(34))))
                      ],
                    );
                  });
            },
            pagination: SwiperPagination(
                margin: const EdgeInsets.all(0.0),
                builder: SwiperCustomPagination(
                    builder: (BuildContext context, SwiperPluginConfig config) {
                  return ConstrainedBox(
                      constraints: BoxConstraints.expand(
                          height: ScreenAdapter.height(20)),
                      child: Row(children: <Widget>[
                        Expanded(
                            child: Align(
                                alignment: Alignment.center,
                                child: const RectSwiperPaginationBuilder(
                                        color: Colors.black12,
                                        activeColor: Colors.black54)
                                    .build(context, config)))
                      ]));
                }))),
      ),
    );
  }

  Widget _banner2() {
    return Padding(
      padding: EdgeInsets.fromLTRB(ScreenAdapter.width(20),
          ScreenAdapter.width(20), ScreenAdapter.width(20), 0),
      child: Container(
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(ScreenAdapter.width(20)),
            image: const DecorationImage(
                image: AssetImage("assets/images/xiaomiBanner2.png"),
                fit: BoxFit.cover)),
        height: ScreenAdapter.height(420),
      ),
    );
  }

  Widget _bestSelling() {
    return Column(
      children: [
        Padding(
            padding: EdgeInsets.fromLTRB(
                ScreenAdapter.width(30),
                ScreenAdapter.width(40),
                ScreenAdapter.width(30),
                ScreenAdapter.width(20)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text("热销臻选",
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: ScreenAdapter.fontSize(46))),
                Text("更多手机推荐 >",
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: ScreenAdapter.fontSize(38)))
              ],
            )),
        Padding(
          padding: EdgeInsets.fromLTRB(ScreenAdapter.width(20), 0,
              ScreenAdapter.width(20), ScreenAdapter.width(20)),
          child: Row(
            children: [
              // 左侧
              Expanded(
                flex: 1,
                child: SizedBox(
                    height: ScreenAdapter.height(738),
                    child: Obx(() => Swiper(
                        itemCount: controller.bestSellingSwiperList.length,
                        itemBuilder: (context, index) {
                          String picUrl =
                              "https://xiaomi.itying.com/${controller.bestSellingSwiperList[index].pic}";
                          return Image.network(picUrl.replaceAll("\\", "/"),
                              fit: BoxFit.fill);
                        },
                        autoplay: true,
                        loop: true,
                        pagination: SwiperPagination(
                            margin: const EdgeInsets.all(0.0),
                            builder: SwiperCustomPagination(builder:
                                (BuildContext context,
                                    SwiperPluginConfig config) {
                              return ConstrainedBox(
                                  constraints: BoxConstraints.expand(
                                      height: ScreenAdapter.height(20)),
                                  child: Row(children: <Widget>[
                                    Expanded(
                                        child: Align(
                                            alignment: Alignment.center,
                                            child:
                                                const RectSwiperPaginationBuilder(
                                                        color: Colors.black12,
                                                        activeColor:
                                                            Colors.black54)
                                                    .build(context, config)))
                                  ]));
                            }))))),
              ),
              SizedBox(
                width: ScreenAdapter.width(20),
              ),
              // 右侧
              Expanded(
                  flex: 1,
                  child: SizedBox(
                      height: ScreenAdapter.height(738),
                      child: Obx(() => Column(
                            children: controller.sellingPlist
                                .asMap()
                                .entries
                                .map((entrie) {
                              var value = entrie.value;
                              var picUrl =
                                  "https://xiaomi.itying.com/${value.pic}";

                              return Expanded(
                                  flex: 1,
                                  child: Container(
                                      color: const Color.fromRGBO(
                                          246, 246, 246, 1),
                                      margin: EdgeInsets.fromLTRB(
                                        0,
                                        0,
                                        0,
                                        entrie.key == 2
                                            ? 0
                                            : ScreenAdapter.height(20),
                                      ),
                                      child: Row(
                                        children: [
                                          // 左边
                                          Expanded(
                                              flex: 3,
                                              child: Column(
                                                children: [
                                                  SizedBox(
                                                      height:
                                                          ScreenAdapter.height(
                                                              15)),
                                                  Text(
                                                    "${value.title}",
                                                    style: TextStyle(
                                                        fontSize: ScreenAdapter
                                                            .fontSize(38),
                                                        fontWeight:
                                                            FontWeight.bold),
                                                  ),
                                                  SizedBox(
                                                      height:
                                                          ScreenAdapter.height(
                                                              15)),
                                                  Text("${value.subTitle}",
                                                      style: TextStyle(
                                                          fontSize:
                                                              ScreenAdapter
                                                                  .fontSize(
                                                                      28))),
                                                  SizedBox(
                                                      height:
                                                          ScreenAdapter.height(
                                                              15)),
                                                  Text("￥${value.price}元",
                                                      style: TextStyle(
                                                          fontSize:
                                                              ScreenAdapter
                                                                  .fontSize(
                                                                      34)))
                                                ],
                                              )),
                                          Expanded(
                                              flex: 2,
                                              child: Padding(
                                                  padding: EdgeInsets.all(
                                                      ScreenAdapter.height(8)),
                                                  child: Image.network(
                                                      picUrl.replaceAll(
                                                          "\\", "/"),
                                                      fit: BoxFit.cover)))
                                        ],
                                      )));
                            }).toList(),
                          ))))
            ],
          ),
        )
      ],
    );
  }

  // 热门商品
  Widget _bestGoods() {
    return Column(children: [
      Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenAdapter.width(30),
            ScreenAdapter.width(40),
            ScreenAdapter.width(30),
            ScreenAdapter.width(20)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text("省心优惠",
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: ScreenAdapter.fontSize(46))),
            Text("全部优惠 >",
                style: TextStyle(fontSize: ScreenAdapter.fontSize(38))),
          ],
        ),
      ),
      Obx(() => Container(
            padding: EdgeInsets.all(ScreenAdapter.width(26)),
            color: const Color.fromRGBO(246, 246, 246, 1),
            child: MasonryGridView.count(
                crossAxisCount: 2,
                mainAxisSpacing: ScreenAdapter.width(26),
                crossAxisSpacing: ScreenAdapter.width(26),
                itemCount: controller.bestPlist.length,
                shrinkWrap: true, // 收缩，让元素宽度自适应
                physics: const NeverScrollableScrollPhysics(), // 禁止滑动
                itemBuilder: (context, index) {
                  return InkWell(
                    onTap: () {
                      Get.toNamed("/product-content",
                          arguments: {"id": controller.bestPlist[index].sId});
                    },
                    child: Container(
                      padding: EdgeInsets.all(ScreenAdapter.width(20)),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: Colors.white),
                      child: Column(children: [
                        Container(
                          padding: EdgeInsets.all(ScreenAdapter.width(10)),
                          child: Image.network(
                              HttpsClient.replaceUrl(
                                  controller.bestPlist[index].sPic),
                              fit: BoxFit.cover),
                        ),
                        Container(
                          padding: EdgeInsets.all(ScreenAdapter.width(10)),
                          width: double.infinity,
                          child: Text("${controller.bestPlist[index].title}",
                              textAlign: TextAlign.start,
                              style: TextStyle(
                                  fontSize: ScreenAdapter.fontSize(42),
                                  fontWeight: FontWeight.bold)),
                        ),
                        Container(
                          padding: EdgeInsets.all(ScreenAdapter.width(10)),
                          width: double.infinity,
                          child: Text(
                            "${controller.bestPlist[index].subTitle}",
                            textAlign: TextAlign.start,
                            style:
                                TextStyle(fontSize: ScreenAdapter.fontSize(32)),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.all(ScreenAdapter.width(10)),
                          width: double.infinity,
                          child: Text(
                            "¥${controller.bestPlist[index].price}",
                            textAlign: TextAlign.start,
                            style: TextStyle(
                                fontSize: ScreenAdapter.fontSize(32),
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                      ]),
                    ),
                  );
                }),
          ))
    ]);
  }

  Widget _homePage() {
    return Positioned(
        top: -40,
        left: 0,
        right: 0,
        bottom: 0,
        child: ListView(
          controller: controller.scrollController,
          children: [
            _focus(),
            _banner(),
            _category(),
            _banner2(),
            _bestSelling(),
            _bestGoods()
          ],
        ));
  }

  Widget _appBar() {
    return Positioned(
        top: 0,
        left: 0,
        right: 0,
        child: Obx(() => AppBar(
              leading: controller.isGetOut.value
                  ? const Text("")
                  : const Icon(DuanzihuangFonts.xiaomi, color: Colors.white),
              leadingWidth: controller.isGetOut.value
                  ? ScreenAdapter.width(40)
                  : ScreenAdapter.width(140),
              title: InkWell(
                child: AnimatedContainer(
                  width: controller.isGetOut.value
                      ? ScreenAdapter.width(800)
                      : ScreenAdapter.width(620),
                  height: ScreenAdapter.width(96),
                  decoration: BoxDecoration(
                      color: const Color.fromARGB(230, 252, 243, 236),
                      borderRadius: BorderRadius.circular(30)),
                  duration: const Duration(milliseconds: 600),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Padding(
                          padding: EdgeInsets.fromLTRB(ScreenAdapter.width(34),
                              0, ScreenAdapter.width(10), 0),
                          child: const Icon(Icons.search)),
                      Text("手机",
                          style: TextStyle(
                              color: Colors.black54,
                              fontSize: ScreenAdapter.fontSize(32)))
                    ],
                  ),
                ),
                onTap: () {
                  Get.toNamed("/search");
                },
              ),
              centerTitle: true,
              backgroundColor: controller.isGetOut.value
                  ? Colors.white
                  : Colors.transparent, // 实现透明导航
              elevation: 0, // 实现透明导航
              actions: [
                IconButton(
                    onPressed: () {},
                    icon: Icon(Icons.qr_code,
                        color: controller.isGetOut.value
                            ? Colors.black87
                            : Colors.white)),
                IconButton(
                    onPressed: () {},
                    icon: Icon(Icons.message,
                        color: controller.isGetOut.value
                            ? Colors.black87
                            : Colors.white))
              ],
            )));
  }

  @override
  Widget build(BuildContext context) {
    return KeepAliveWrapper(
        child: Scaffold(
            body: Stack(
      children: [_homePage(), _appBar()],
    )));
  }
}
